package com.example.demo.file;

import com.example.demo.module.pojo.JobInfo;
import com.example.demo.module.pojo.Salary;
import lombok.Data;

import java.io.*;
import java.util.ArrayList;

/**
 * @author MarioZzz
 * @create 2024-07-04 9:24
 */
public class TransientDemo {

    /**
     * transient字段不会被序列化, 反序列化时，transient字段的值为默认值
     *
     * @param args
     */
    public static void main(String[] args) {
//        Person person = new Person();
//        person.name = "Mario";
//        person.age = 18;
//        System.out.println("TransientDemo.main,before transient");
//        System.out.println(person.name);
//        System.out.println(person.age);
//
//        try {
//            ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("D:/person.txt"));
//            // 序列化
//            os.writeObject(person);
//            os.flush();
//            os.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        try {
//            ObjectInputStream is = new ObjectInputStream(new FileInputStream("D:/person.txt"));
//            Person person1 = (Person) is.readObject();
//            is.close();
//            System.out.println("TransientDemo.main,after transient");
//            System.out.println(person1.name);
//            System.out.println(person1.age);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }

        JobInfo jobInfo = new JobInfo();
        jobInfo.setJobName("java");
        ArrayList<Salary> salaries = new ArrayList<>();
        salaries.add(new Salary(1000, 2000));
        jobInfo.setSalaryList(salaries);
        System.out.println("TransientDemo.main,before transient");
        System.out.println(jobInfo.getJobName());
        System.out.println(jobInfo.getSalaryList());

        try {
            ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("D:/person.txt"));
            // 序列化
            os.writeObject(jobInfo);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            ObjectInputStream is = new ObjectInputStream(new FileInputStream("D:/person.txt"));
            JobInfo person1 = (JobInfo) is.readObject();
            is.close();
            System.out.println("TransientDemo.main,after transient");
            System.out.println(person1.getJobName());
            System.out.println(person1.getSalaryList());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Data
    static class Person implements Serializable {
        private String name;
        private transient int age;
    }
}
